package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @program: minicat
 * @description
 * @author: luffy
 * @create: 2020-08-02 21:39
 */
public class StaticResourceUtil {
    /**
     * 获取静态资源的绝对路径
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path) throws URISyntaxException {
       URI uri = StaticResourceUtil.class.getResource("/").toURI();
        String absolutePath = uri.getPath();
        System.out.println("absolutePath = " + absolutePath);
        return absolutePath.replaceAll("\\\\", "/") + path;
    }

    public static void outPutStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }
        int resourceSize = count;
        //输出Http请求头
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());

        //读取内容输出
        //已经读取的内容长度
        long written = 0;
        //计划每次缓冲的长度
        int byteSize = 1024;

        byte[] bytes = new byte[byteSize];

        while (written < resourceSize) {
            //说明剩余读取大小不足一个1024长度，就按照真实长度处理
            if (written + byteSize > resourceSize) {
                //剩余文件内容长度
                byteSize = (int) (resourceSize - written);
                bytes = new byte[byteSize];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);

            outputStream.flush();

            written += byteSize;
        }

    }
}
